<!--月度锁账日报表-->
<script setup lang="ts">
    defineOptions({
        name: "LockReport",
        inheritAttrs: false,
    });

    import {ElLoading, UploadFile} from "element-plus";
		import {
			getSysLockDailyRecordPage,
			getSysLockDailyRecordForm,
			saveSysLockDailyRecord,
			deleteSysLockDailyRecord,
			importSysLockDailyRecord,
			exportSysLockDailyRecord,
			getSummaryRecord
		} from "@/api/lockBillReport";
		import {getByStoreKey} from "@/api/store";
		import {getPlatformList} from "@/api/platform";
		import moment from "moment/moment";
		import lodash from 'lodash-es'

    const queryFormRef = ref(ElForm);
    const dataFormRef = ref(ElForm);

    const loading = ref(false);
    const summaryLoading = ref(false);
    const ids = ref<number[]>([]);
    const total = ref(0);
    const activeTab = ref<any>('one');
		const storeList = ref<[]>([])
		const platformList = ref<[]>([])
		const dateList = ref<[]>([])

    const queryParams = reactive<any>({
        pageNum: 1,
        pageSize: 20,
    });
		const summaryQueryParams = reactive<any>({
			pageNum: 1,
			pageSize: 20,
		});

    const sysLockDailyRecordList = ref<[]>();
    const summaryList = ref<[]>();

    const dialog = reactive<DialogOption>({
        visible: false,
    });
    const importDialog = reactive<DialogOption>({
        title: "月度锁账日报表数据导入",
        visible: false,
    });

    const excelFile = ref<File>();
    const excelFilelist = ref<File[]>([]);
    const formData = reactive<any>({});

    const rules = reactive({
        platformId: [{ required: true, message: "请输入平台ID", trigger: "blur" }],
        storeId: [{ required: true, message: "请输入店铺ID", trigger: "blur" }],
        businessDate: [{ required: true, message: "请输入业务日期", trigger: "blur" }],
        sendAmount: [{ required: true, message: "请输入发货金额", trigger: "blur" }],
        returnAmount: [{ required: true, message: "请输入退货金额", trigger: "blur" }],
        receiveBillAmount: [{ required: true, message: "请输入退货金额", trigger: "blur" }],
    });




    /**
     * 查询
     */
    function handleQuery() {
			if (activeTab.value === 'one') {
				loading.value = true;
				if (lodash.size(dateList.value) > 0){
					lodash.set(queryParams, 'startBusinessDate', dateList.value[0])
					lodash.set(queryParams, 'endBusinessDate', dateList.value[1])
				}else{
					queryParams.startDate = ''
					queryParams.endDate = ''
				}
				getSysLockDailyRecordPage(queryParams)
					.then(({ data }) => {
						sysLockDailyRecordList.value = data.list;
						total.value = data.total;
					})
					.finally(() => {
						loading.value = false;
					});
			}else{
				summaryLoading.value = true;
				getSummaryRecord(summaryQueryParams)
					.then(( response ) => {
						summaryList.value = response.data;
					})
					.finally(() => {
						summaryLoading.value = false;
					});
			}
    }

    /**
     * 重置查询
     */
    function resetQuery() {
        queryFormRef.value.resetFields();
        queryParams.pageNum = 1;
        handleQuery();
    }

    /**
     * 行checkbox change事件
     */
    function handleSelectionChange(selection: any) {
        ids.value = selection.map((item: any) => item.id);
    }

    /**
     * 打开字典类型表单弹窗
     *
     * @param dicTypeId 字典类型ID
     */
    function openDialog(id?: number) {
        dialog.visible = true;
        if (id) {
            dialog.title = "修改月度锁账日报表";
            getSysLockDailyRecordForm(id).then(({ data }) => {
                Object.assign(formData, data);
            });
        } else {
            dialog.title = "新增月度锁账日报表";
        }
    }

    /**
     * 字典类型表单提交
     */
    function handleSubmit() {
        dataFormRef.value.validate((isValid: boolean) => {
            if (isValid) {
                loading.value = false;
                saveSysLockDailyRecord(formData)
                    .then(() => {
                        ElMessage.success("保存成功");
                        closeDialog();
                        handleQuery();
                    })
                    .finally(() => (loading.value = false));
            }
        });
    }

    /**
     * 关闭弹窗
     */
    function closeDialog() {
        dialog.visible = false;
        resetForm();
    }

    /**
     * 重置表单
     */
    function resetForm() {
        dataFormRef.value.resetFields();
        dataFormRef.value.clearValidate();

        formData.id = undefined;
    }

    /**
     * 删除月度锁账日报表
     */
    function handleDelete(id?: number) {
        const dictTypeIds = [id || ids.value].join(",");
        if (!dictTypeIds) {
            ElMessage.warning("请勾选删除项");
            return;
        }

        ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        }).then(() => {
            deleteSysLockDailyRecord(dictTypeIds).then(() => {
                ElMessage.success("删除成功");
                resetQuery();
            });
        });
    }

    /** 打开导入弹窗 */
    async function openImportDialog() {
        importDialog.visible = true;
    }

    /**
     * Excel文件change事件
     *
     * @param file
     */
    function handleExcelChange(file: UploadFile) {
        if (file.size !== undefined) {
            if (file.size > 20*1024*1024) {
                ElMessage.warning("上传文件大小不能超过20M");
                return false
            }
        }
        if (!/\.(xlsx|xls|XLSX|XLS)$/.test(file.name)) {
            ElMessage.warning("上传Excel只能为xlsx、xls格式");
            excelFile.value = undefined;
            excelFilelist.value = [];
            return false;
        }
        excelFile.value = file.raw;
    }

    /** 导入提交 */
    function handleImport() {
        if (!excelFile.value) {
            ElMessage.warning("上传Excel文件不能为空");
            return false;
        }
        const importLoading = ElLoading.service({
            lock: true,
            text: '导入中...',
            background: 'rgba(0, 0, 0, 0.7)',
        })
        importSysLockDailyRecord(excelFile.value).then((response) => {

            closeImportDialog();
            ElMessage.success('导入成功');
            resetQuery();
        }).finally(() => importLoading.close());
    }

    /**  关闭导入弹窗 */
    function closeImportDialog() {
        importDialog.visible = false;
        excelFile.value = undefined;
        excelFilelist.value = [];
    }

    /** 导出月度锁账日报表 */
    function handleExport() {
        const strIds = [ids.value].join(",");
        exportSysLockDailyRecord(strIds).then((response: any) => {
            const blob = new Blob([response.data], {
                type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
            });
            const a = document.createElement("a");
            const href = window.URL.createObjectURL(blob); // 下载的链接
            a.href = href;
            a.download = decodeURI(
                response.headers["content-disposition"].split(";")[1].split("=")[1]
            ); // 获取后台设置的文件名称
            document.body.appendChild(a);
            a.click(); // 点击导出
            document.body.removeChild(a); // 下载完成移除元素
            window.URL.revokeObjectURL(href); // 释放掉blob对象
        });
    }

		function handleGetPlatformList() {
			getPlatformList().then((response) => {
				platformList.value = response.data
			})
		}

		function getStoreList() {
			queryParams.storeId = null
			summaryQueryParams.storeId = null
			storeList.value = []
			if (activeTab.value === 'one') {
				if (queryParams.platformId !== null && queryParams.platformId !== undefined) {
					let platform = lodash.find(platformList.value, (item: any) => item.id === queryParams.platformId)
					getByStoreKey(platform.platformKey).then((response) => {
						storeList.value = response.data
					})
				}
			}else{
				if (summaryQueryParams.platformId !== null && summaryQueryParams.platformId !== undefined) {
					let platform = lodash.find(platformList.value, (item: any) => item.id === summaryQueryParams.platformId)
					getByStoreKey(platform.platformKey).then((response) => {
						storeList.value = response.data
					})
				}
			}
		}

    onMounted(() => {
				dateList.value.push(moment().subtract(1, 'days').format('YYYY-MM-DD'))
				dateList.value.push(moment().subtract(1, 'days').format('YYYY-MM-DD'))
				handleGetPlatformList()
        handleQuery();
    });
</script>

<template>
    <div class="app-container">
			<el-row :gutter="20">
				<el-col>
					<div class="search-container">
						<el-form v-if="activeTab === 'one'" ref="queryFormRef" :inline="true">
							<el-form-item label="业务日期">
								<el-date-picker
									v-model="dateList"
									style="width: 250px"
									type="daterange"
									:clearable="false"
									range-separator="至"
									start-placeholder="开始日期"
									end-placeholder="结束日期"
									value-format="YYYY-MM-DD"
								/>
							</el-form-item>
							<el-form-item label="平台" prop="platformId">
								<el-select v-model="queryParams.platformId" class="yz-el-select"  clearable placeholder="请选择" @change="getStoreList">
									<el-option
										v-for="item in platformList"
										:key="item.id"
										:label="item.reconciliationSystemName"
										:value="item.id"
									/>
								</el-select>
							</el-form-item>
							<el-form-item label="店铺" prop="storeId">
								<el-select v-model="queryParams.storeId" class="yz-el-select" clearable placeholder="请选择">
									<el-option
										v-for="item in storeList"
										:key="item.id"
										:label="item.commercePlatformStoreName"
										:value="item.id"
									/>
								</el-select>
							</el-form-item>
							<el-form-item>
								<el-button type="primary" @click="handleQuery()"
								><i-ep-search />搜索</el-button
								>
								<el-button @click="resetQuery()"><i-ep-refresh />重置</el-button>
							</el-form-item>
						</el-form>
						<el-form v-else ref="queryFormRef" :inline="true">
							<el-form-item label="周期">
								<el-date-picker
									v-model="summaryQueryParams.billMonth"
									style="width: 200px"
									type="month"
									:clearable="false"
									value-format="YYYY-MM"
								/>
							</el-form-item>
							<el-form-item label="平台" prop="platformId">
								<el-select v-model="summaryQueryParams.platformId" class="yz-el-select" clearable placeholder="请选择" @change="getStoreList">
									<el-option
										v-for="item in platformList"
										:key="item.id"
										:label="item.reconciliationSystemName"
										:value="item.id"
									/>
								</el-select>
							</el-form-item>
							<el-form-item label="店铺" prop="storeId">
								<el-select v-model="summaryQueryParams.storeId" class="yz-el-select" clearable placeholder="请选择">
									<el-option
										v-for="item in storeList"
										:key="item.id"
										:label="item.commercePlatformStoreName"
										:value="item.id"
									/>
								</el-select>
							</el-form-item>
							<el-form-item>
								<el-button type="primary" @click="handleQuery()"
								><i-ep-search />搜索</el-button
								>
								<el-button @click="resetQuery()"><i-ep-refresh />重置</el-button>
							</el-form-item>
						</el-form>
					</div>

					<el-card shadow="never">
						<template #header>
							<div class="flex justify-between">
								<div>
									<el-button
										v-hasPerm="['sys:lockDailyRecord:save']"
										type="success"
										@click="openDialog()"
									><i-ep-plus />新增</el-button
									>
									<el-button
										type="danger"
										:disabled="ids.length === 0"
										@click="handleDelete()"
										v-hasPerm="['sys:lockDailyRecord:delete']"
									><i-ep-delete />删除</el-button
									>
								</div>
								<div>
									<el-button class="ml-3" @click="openImportDialog" v-hasPerm="['sys:lockDailyRecord:import']"
									><template #icon><i-ep-top /></template>导入</el-button
									>
									<el-button class="ml-3" @click="handleExport" v-hasPerm="['sys:lockDailyRecord:export']"
									><template #icon><i-ep-download /></template>导出</el-button
									>
								</div>
							</div>
						</template>
						<el-tabs v-model="activeTab" type="border-card" @tab-click="handleQuery">
							<el-tab-pane label="日统计" name="one">
								<el-table
									v-loading="loading"
									size="small"
									:header-row-style="{color: 'dimgray'}"
									highlight-current-row
									:data="sysLockDailyRecordList"
									border
									:height="sysLockDailyRecordList && sysLockDailyRecordList.length > 0 ? 530 : 130"
								>
									<el-table-column label="平台" prop="platformName" width="100" show-overflow-tooltip/>
									<el-table-column label="店铺" prop="storeName" width="140" show-overflow-tooltip/>
									<el-table-column label="业务日期" prop="businessDate" width="120" show-overflow-tooltip/>
									<el-table-column label="发货金额" prop="sendAmount" width="120" show-overflow-tooltip>
										<template #default="scope">
											<format-money :value="scope.row.sendAmount"></format-money>
										</template>
									</el-table-column>
									<el-table-column label="退货金额" prop="returnAmount" width="120" show-overflow-tooltip>
										<template #default="scope">
											<format-money :value="scope.row.returnAmount"></format-money>
										</template>
									</el-table-column>
									<el-table-column label="收入金额" prop="receiveAmount" width="120" show-overflow-tooltip>
										<template #default="scope">
											<format-money :value="scope.row.receiveAmount"></format-money>
										</template>
									</el-table-column>
									<el-table-column label="应收账款金额" prop="receiveBillAmount" width="120" show-overflow-tooltip>
										<template #default="scope">
											<format-money :value="scope.row.receiveBillAmount"></format-money>
										</template>
									</el-table-column>
								</el-table>

								<pagination
									v-if="total > 0"
									v-model:total="total"
									v-model:page="queryParams.pageNum"
									v-model:limit="queryParams.pageSize"
									@pagination="handleQuery"
								/>
							</el-tab-pane>
							<el-tab-pane label="关账统计" name="two">
								<el-table
									v-loading="summaryLoading"
									size="small"
									:header-row-style="{color: 'dimgray'}"
									highlight-current-row
									:data="summaryList"
									border
									:height="summaryList && summaryList.length > 0 ? 580 : 130"
								>
									<el-table-column label="平台" prop="platformName" show-overflow-tooltip/>
									<el-table-column label="店铺" prop="storeName" width="140" show-overflow-tooltip/>
									<el-table-column label="周期" prop="billMonth" width="100" show-overflow-tooltip/>
									<el-table-column label="锁账状态" prop="status" width="80" show-overflow-tooltip/>
									<el-table-column align="center" label="期初">
										<el-table-column label="发货金额" width="100" show-overflow-tooltip>
											<template #default="scope">
												<format-money :value="scope.row.beginItem.sendAmount"></format-money>
											</template>
										</el-table-column>
										<el-table-column label="退货金额" width="100" show-overflow-tooltip>
											<template #default="scope">
												<format-money :value="scope.row.beginItem.returnAmount"></format-money>
											</template>
										</el-table-column>
										<el-table-column label="收入金额" width="100" show-overflow-tooltip>
											<template #default="scope">
												<format-money :value="scope.row.beginItem.receiveAmount"></format-money>
											</template>
										</el-table-column>
										<el-table-column label="应收账款金额" width="100" show-overflow-tooltip>
											<template #default="scope">
												<format-money :value="scope.row.beginItem.receiveBillAmount"></format-money>
											</template>
										</el-table-column>
									</el-table-column>
									<el-table-column align="center" label="本期发生">
										<el-table-column label="发货金额" width="100" show-overflow-tooltip>
											<template #default="scope">
												<format-money :value="scope.row.currentItem.sendAmount"></format-money>
											</template>
										</el-table-column>
										<el-table-column label="退货金额" width="100" show-overflow-tooltip>
											<template #default="scope">
												<format-money :value="scope.row.currentItem.returnAmount"></format-money>
											</template>
										</el-table-column>
										<el-table-column label="收入金额" width="100" show-overflow-tooltip>
											<template #default="scope">
												<format-money :value="scope.row.currentItem.receiveAmount"></format-money>
											</template>
										</el-table-column>
										<el-table-column label="应收账款金额" width="100" show-overflow-tooltip>
											<template #default="scope">
												<format-money :value="scope.row.currentItem.receiveBillAmount"></format-money>
											</template>
										</el-table-column>
									</el-table-column>
									<el-table-column align="center" label="期末">
										<el-table-column label="发货金额" width="100" show-overflow-tooltip>
											<template #default="scope">
												<format-money :value="scope.row.endItem.sendAmount"></format-money>
											</template>
										</el-table-column>
										<el-table-column label="退货金额" width="100" show-overflow-tooltip>
											<template #default="scope">
												<format-money :value="scope.row.endItem.returnAmount"></format-money>
											</template>
										</el-table-column>
										<el-table-column label="收入金额" width="100" show-overflow-tooltip>
											<template #default="scope">
												<format-money :value="scope.row.endItem.receiveAmount"></format-money>
											</template>
										</el-table-column>
										<el-table-column label="应收账款金额" width="100" show-overflow-tooltip>
											<template #default="scope">
												<format-money :value="scope.row.endItem.receiveBillAmount"></format-money>
											</template>
										</el-table-column>
									</el-table-column>
								</el-table>
							</el-tab-pane>
						</el-tabs>
					</el-card>
				</el-col>
			</el-row>
    </div>
</template>
